package com.todoit.wavebot.server;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.todoit.wavebot.util.JdoUser;
import com.todoit.wavebot.util.PMF;
import com.todoit.wavebot.util.TodoitTask;
import com.todoit.wavebot.util.TodoitTaskList;


@SuppressWarnings("serial")
public class XmppReceiverServlet extends HttpServlet {
	private static final XMPPService xmppService = 
	      XMPPServiceFactory.getXMPPService(); 
	
	private PersistenceManager pm = PMF.get().getPersistenceManager();

	private TodoitTaskList dummyTaskList = new TodoitTaskList();
	
	  public void doPost(HttpServletRequest request, HttpServletResponse response) 
	      throws IOException {
		  
		  TodoitTaskList myTaskList;
		  JdoUser myJdoUser;

		  Message message = xmppService.parseMessage(request);
		  
		  try {
	    		// detaching is the key word. why isn't it default behavior?
	    		// the gods of programming know.
	    		while (pm.isClosed())
	    		{
	    			pm = PMF.get().getPersistenceManager(); // give this a shot.
	    		}
	    		// sendXmppMessage(DebugUser, "Getting the object. Debug: "+ pm.getDetachAllOnCommit());
	    		myJdoUser = pm.getObjectById(JdoUser.class, message.getFromJid().getId());
	    		// sendXmppMessage(DebugUser, "We really really want it.");
	    		pm.retrieve(myJdoUser);
	    		pm.makeTransient(myJdoUser);
	    		// sendXmppMessage(DebugUser, "Yes, and its task list too.");
	    		pm.makeTransientAll(myJdoUser.getTaskList());
	    		// myJdoUser = pm.detachCopy(pmJdoUser);
	    		// sendXmppMessage(DebugUser, "Now can we please, god forbid, use it?");
	    		myTaskList = (TodoitTaskList) myJdoUser.getTaskList();
		  }
		  catch (JDOObjectNotFoundException j)
	    	{
			  // create an empty one.
			  myTaskList = new TodoitTaskList();
			  myJdoUser = new JdoUser(message.getFromJid().getId(), null, myTaskList);
	   			pm.makePersistentAll(myJdoUser.getTaskList());
	   			pm.makePersistent(myJdoUser);
	    	};
		  
        // replyToMessage(message, "Diagnostics reply");
	    
	    if (message.getBody().startsWith("task ")) {
	      String taskText = message.getBody().replaceFirst("task ", "");
	      replyToMessage(message, "Trying to fetch JDO.");
	      myJdoUser = pm.getObjectById(JdoUser.class, message.getFromJid().getId());
	      myTaskList = myJdoUser.getTaskList();
	      myTaskList.add(new TodoitTask("taskText", message.getFromJid().getId()));
	      replyToMessage(message, "Trying to modify...");
	      myJdoUser.setTaskList(myTaskList);
	      replyToMessage(message, "Task created.");
	    }
	    else
	    if (message.getBody().startsWith("postpone")) { 
	      String questionText = message.getBody().replaceFirst("postpone", ""); 
	      // call task postpone - add 5 minutes to the reminder date of tasks
	      replyToMessage(message, "Postponed for 5 minutes");
	    }
	    else
		if (message.getBody().startsWith("status")) {
			replyToMessage(message, "Task status:");
			String reply = "";
			for (TodoitTask t : myTaskList)
			{
				reply = reply + t.id + "\t" + t.title + "\n";
			}
			if (""==reply) reply="No tasks found";
			replyToMessage(message, reply);
		}
	    else
	    if (message.getBody().startsWith("dismiss")) {
	    	replyToMessage(message, "Reminder disabled.");
	    }
	    else
	    if (message.getBody().startsWith("help")) { 
	    	replyToMessage(message, "Supported commands:");
	    	replyToMessage(message, "task <taskname> - creates a new task\n" +
	    			"postpone [all | <task id>] - postpones reminder for 5 minutes\n" +
	    			"dismiss [all | <task id>] - cancels reminder\n" +
	    			"status - shows all tasks status\n" +
	    			"help - shows this help screen");
	    	
	    } else { 
	      // respond "error: unrecognized command"
	    	replyToMessage(message, "Unrecognized command.");
	      // followed by handleAnswer(message); 
	    	replyToMessage(message, "Supported commands:");
	    	replyToMessage(message, "task <taskname> - creates a new task\n" +
	    			"postpone [all | <task id>] - postpones reminder for 5 minutes\n" +
	    			"dismiss [all | <task id>] - cancels reminder\n" +
	    			"status - shows all tasks status\n" +
	    			"help - shows this help screen");
	    	
	    }
	    
	  }
	  
	  private void replyToMessage(Message message, String body) {
		    Message reply = new MessageBuilder()
		        .withRecipientJids(message.getFromJid())
		        .withMessageType(MessageType.NORMAL)
		        .withBody(body)
		        .build();

		    xmppService.sendMessage(reply);
		  }


}
